package com.zhangzhan.handler;

import com.alibaba.fastjson.JSON;
import com.zhangzhan.domain.commcon.ResponseResult;
import com.zhangzhan.domain.enums.AppHttpCodeEnum;
import com.zhangzhan.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 张一恒
 * @version 1.0
 */
//security认证异常捕获
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //打印异常
        e.printStackTrace();
        //设置状态码和异常信息然后传到浏览器
        //设置异常类型根据不同的异常类型响应不同的结果
        //BadCredentialsException 账号密码错误
        //InsufficientAuthenticationException  没携带token
        ResponseResult result = null;
        if(e instanceof BadCredentialsException){
            result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(),e.getMessage());
        }else if(e instanceof InsufficientAuthenticationException){
            result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }else{
            result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),"认证失败");
        }
        WebUtils.renderString(httpServletResponse, JSON.toJSONString(result));


    }
}
